import os
import sys
import time
import numpy as np
import SimpleITK as stk
import tensorflow as tf

class utils:
    def Read_Image(self,path):
        nii   = stk.ReadImage(path)
        image = stk.GetArrayFromImage(nii)
        return image

    def one_hot(self,mat,channel=0,on_value=1,off_value=0):
        if(channel == 0):
            channel = np.max(mat) + 1

        assert np.max(mat) != channel,"分类不符合规格" 
        # *arguments is in the way of tuple or list.
        # **arguments is in the way of dict.
        out = np.ones((*mat.shape,channel),np.uint8) * off_value
        indices = []
        for i in range(mat.ndim):
            tiles   = [1] * mat.ndim
            shape   = [1] * mat.ndim
            shape[i]= -1
            row     = np.arange(mat.shape[i]).reshape(shape)
            if i > 0:
                tiles[i-1] = mat.shape[i-1]
                row = np.tile(row, tiles)
            indices.append(row)
        indices.append(mat)
        out[tuple(indices)] = on_value
        return out

    def getParentDirectoryPath(self):
        return os.path.dirname(os.getcwd())

    def dice_(self,y_true,y_pred,smooth=0):
        # 进行运算的是0-1正则化之后的
        pre_num = tf.reduce_sum(y_pred)
        tru_num = tf.reduce_sum(y_true)
        cross_area = y_pred*y_true
        cro_num = tf.reduce_sum(cross_area)
        cro_    = (2*cro_num+smooth)/(pre_num + tru_num + smooth)
        return cro_

    def softmax_norm(self,y_pred):
        # 输出的是softmax之后的概率值从而导致结果不纯净，所以需要进行处理
        temp1 = tf.argmax(y_pred,axis=-1)
        y_pred_norm = tf.one_hot(temp1,y_pred.shape[-1],1,0)
        y_pred_norm = tf.cast(y_pred_norm,dtype=tf.float32)
        return y_pred_norm

    def global_dice(self,y_true,y_pred):
        y_pred_norm = self.softmax_norm(y_pred)
        return self.dice_(y_true[:,:,:,1:],y_pred_norm[:,:,:,1:])

    def get_new(self,dir):
        # 获得某个目录下创建时间最晚的文件，最新的文件
        map = lambda x:os.path.getctime(os.path.join(dir,x))
        file_list = os.listdir(dir)
        new = sorted(file_list,key=map,reverse=True)[0]
        return new,time.localtime(map(new))

if __name__ == "__main__":
    a = np.array([[[1,2],[3,4]],[[1,2],[3,4]]])
    print(utils().one_hot(a))
    # print(out.shape)
    # print(out[np.array([0]),np.array([0]),np.array([0])])

    # a = np.arange(10)
    # print(a)
    # print(a.reshape((1,-1,1,1)))
    # print(a[0])
    # print(one_hot(a))
    # one_hot(a)
    # print(a)
    # print(utils().one_hot(a))
    # print([1]*2)